package cn.schoolwow.starter.quickdao.test;

import cn.schoolwow.quickdao.QuickDAO;
import cn.schoolwow.quickdao.dao.DAO;
import cn.schoolwow.starter.quickdao.Account;
import cn.schoolwow.starter.quickdao.QuickDAOTransactionManager;
import com.zaxxer.hikari.HikariDataSource;
import org.aeonbits.owner.ConfigCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@EnableTransactionManagement
@Configuration
@ComponentScan(basePackages = "cn.schoolwow.starter.quickdao.test")
public class QuickDAOStarterConfig {
    @Bean
    public HikariDataSource hikariDataSource(){
        Account account = ConfigCache.getOrCreate(Account.class);
        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setDriverClassName("org.mariadb.jdbc.Driver");
        hikariDataSource.setJdbcUrl(account.jdbcUrl());
        hikariDataSource.setUsername(account.username());
        hikariDataSource.setPassword(account.password());
        return hikariDataSource;
    }

    @Bean
    @Autowired
    public DAO quickdao(HikariDataSource hikariDataSource){
        DAO dao = QuickDAO.newInstance()
                .dataSource(hikariDataSource)
                .packageName("cn.schoolwow.starter.quickdao.test.entity")
                .charset("utf8")
                .engine("InnoDB")
                .foreignKey(false)
                .build();
        return dao;
    }

    @Bean
    @Autowired
    public PlatformTransactionManager transactionManager(DAO dao){
        PlatformTransactionManager quickDAOTransactionManager = new QuickDAOTransactionManager(dao);
        return quickDAOTransactionManager;
    }
}
